package com.Fate.service.impl;

import com.Fate.common.CodeMsg;
import com.Fate.common.Constant;
import com.Fate.common.PageInfo;
import com.Fate.common.Result;
import com.Fate.dao.UserDao;
import com.Fate.pojo.User;
import com.Fate.service.IUserServiece;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements IUserServiece {
    UserDao userDao = new UserDao();

    @Override
    public Result login(String username, String password) {
        User user = userDao.selectByNameAndPassword(username, password);
        //校验是否存在用户 不存在 说明用户名或者密码错误
        if(user == null){
            return new Result(CodeMsg.USER_NAME_PASSWORD_ERROR);
        }
        //校验用户的状态
        if(user.getDeleted().equals(Constant.USER_DELETE_ED)){
            return new Result(CodeMsg.USER_DELETED_ERROR);
        }
        //将用户信息放入result中是为了在servlet中放入session
        return new Result(user);
    }

    @Override
    public Result queryPage(Map<String, String> params, Integer pageNo, Integer pageSize) {
        PageInfo<User> data = userDao.selectPage(params, pageNo, pageSize);

        return new Result(data);
    }

    @Override
    public Result resetPassword(String id) {
        //查询用户
        userDao.updatePassword(id,Constant.DEFAULT_PASSWORD);

        return new Result();
    }

    @Override
    public Result del(String id) {
        //根据员工ID查询关联的客户，如果该员工存在关联客户 则无法离职
        //TODO 需要根据员工id查询客户，如果存在关联客户，则无法离职
        userDao.del(id,Constant.USER_DELETE_ED);

        return new Result();
    }

    @Override
    public Result add(String username, String realname, Integer role) {
        //校验用户名是否存在
              User user =  userDao.selectByUsername(username);
              if (user!=null){
                  return new Result(CodeMsg.USER_USERNAME_EXIST_ERROR);
              }

        userDao.insert(username,Constant.DEFAULT_PASSWORD,realname,role,Constant.USER_DELETE_NOT);
        return new Result();
    }

    @Override
    public Result queryAllsalesman() {
       List<User> users = userDao.selectList(Constant.USER_DELETE_NOT,Constant.USER_ROLE_SALESMAN);
        return new Result(users);
    }


    @Override
    public Result modify(String password ,Integer id) {
        String ID = String.valueOf(id);
        userDao.updatePassword(ID,password);
        return new Result();
    }
}
